package gr.aueb.cs.mscis.chordroid;

import java.util.Set;

import gr.aueb.cs.mscis.R;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class DHTManagerActivity extends Activity {
	protected InitTask updateField;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dhtmanagerlayout);

		updateField = new InitTask();
		updateField.execute(this);
	}

	protected class InitTask extends AsyncTask<Activity, String, String> {
		// -- run intensive processes here
		// -- notice that the datatype of the first param in the class
		// definition matches the param passed to this method
		// -- and that the datatype of the last param in the class definition
		// matches the return type of this mehtod
		@Override
		protected String doInBackground(Activity... params) {
			// -- on every iteration
			// -- runs a while loop that causes the thread to sleep for 50
			// milliseconds
			// -- publishes the progress - calls the onProgressUpdate handler
			// defined below
			// -- and increments the counter variable i by one
			
			Set<String> set = ChordroidService.getDht().getKeys();
			while (set != null) {
				try {
					Thread.sleep(50);
					String[] values = new String[set.size()]; int i=0;
					for (String key : set) {
						values[i++] = key;
					}
					publishProgress(values);
				}catch (Exception e) {
				}
			}
			
			return "COMPLETE!";
		}

		// -- gets called just before thread begins
		@Override
		protected void onPreExecute() {
			Log.i("makemachine", "onPreExecute()");
			super.onPreExecute();

		}

		// -- called from the publish progress
		// -- notice that the datatype of the second param gets passed to this
		// method
		@Override
		protected void onProgressUpdate(String... values) {
			super.onProgressUpdate(values);
			if (values.length < 1) return;
			((TextView) findViewById(R.id.textView666)).setLines(values.length);
			((TextView) findViewById(R.id.textView666)).setText(values[0] + "\n");
			for (int i=1; i<values.length; i++) {
				CharSequence appendToThis = ((TextView) findViewById(R.id.textView666)).getText();
				((TextView) findViewById(R.id.textView666)).setText(appendToThis + values[i] + "\n");
			}

		}

		// -- called if the cancel button is pressed
		@Override
		protected void onCancelled() {
			super.onCancelled();
			Log.i("makemachine", "onCancelled()");
		}

		// -- called as soon as doInBackground method completes
		// -- notice that the third param gets passed to this method
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			Log.i("makemachine", "onPostExecute(): " + result);

		}
	}

}
